<template>
  <view class="information-update box pd-v-60 flex flex-ver flex-center position-r">
    <view class="mr-t-76 information-update__header">
        
    </view>
    <view class="mr-t-100 information-update__body">
        <u--form
            :model="form"
            :rules="rules"
            ref="uForm"
        >
            <u-form-item
                prop="avatar"
            >
                <button class="avatar-btn" type="default" open-type="chooseAvatar" @chooseavatar="chooseavatar">
                    <image class="border100 border-default" :src="form.avatar ? getFileUrl(form.avatar) : form.avatar" style="width:176rpx;height:176rpx" mode="widthFix" />
                
                    <view class="mr-t-16 font28 lh-40 color-default txt-center">
                        设置头像
                    </view>
                </button>
            </u-form-item>
            <u-form-item
                prop="name"
                borderBottom
            >
                <u--input
                    v-model="form.name"
                    type="nickname"
                    placeholder="请输入昵称"
                    border="none"
                    clearable
                ></u--input>
            </u-form-item>

            
            <u-form-item
                prop="phone"
                borderBottom
            >
                <u--input
                clearable
                    v-model="form.phone"
                    placeholder="请输入手机号"
                    border="none"
                    type="number"
                ></u--input>
            </u-form-item>
        </u--form>
    
        <view class="full-w mr-t-88">
            <u-button class="mr-t-24" type="primary" :customStyle="{height:'88rpx'}" shape="circle" color="#35BE65"  text="保存" @click="save"></u-button>
        </view>
    </view>
      
    
      
      
      
   
      
      
  </view>
</template>

<script setup>

import { useStore } from '@/store/index.js';
import { userUpdate } from "@/api/user";

import { computed, ref, onMounted, reactive } from "vue";
import { onReady } from '@dcloudio/uni-app';
import {upload} from '@/api/index/index'
const FormData = require('../../../static/formdata.js')
import { fileUrl } from '@/utils/index.js'

const store = useStore();

const isWx = ref(false)
const redirectURL = ref('/pages/index/index')
const isCheck = ref(false)
const form = ref({
    name: '',
    phone: '',
    avatar: ''
});
const uForm = ref(null);
const rules = ref({
    name: [
        {
            required: true,
            message: '请输入昵称',
            trigger: ['blur','change']
        }
    ],
    phone: [
        {
            required: true,
            trigger: ['blur','change'],
            validator: (rule, value,callback) => {
                if (!value) {
                    callback('请输入手机号');
                    return false;
                }
                if (!/^1[3-9]\d{9}$/.test(value)) {
                    callback('请输入正确的手机号');
                    return false;
                }
                return true;
            }
        }
    ],
    avatar: [
        {
            required: true,
            message: '请选择头像',
            trigger: ['blur','change']
        }
    ]
});

onReady(() => {
    form.value.name = store?.user?.userInfo?.nikeName
    form.value.phone = store?.user?.userInfo?.phone
    form.value.avatar = store?.user?.userInfo?.userAvatar
    uForm.value.setRules(rules.value);
});
const getFileUrl = (avatar) => {
    console.log(avatar,'avatar')
    return fileUrl(avatar)
}


const chooseavatar = (e) => {
    console.log(e)
    let avatarUrl = e.detail.avatarUrl
    console.log(FormData)
    let formData = new FormData.default();
 
    // 用法
    formData.append("name", "value");      // value 表单值
    formData.appendFile("file", avatarUrl); // filepath 文件路径
    
    // formData.getData() => { 
    //   buffer:<ArrayBuffer>[], // buffer	表单数据的ArrayBuffer对象 
    //   contentType: string,    // http请求Content-Type头部内容
    // } 
    const data = formData.getData();
    console.log(data)
    upload(data).then(res => {
        console.log(res)
        if(res.code == 200) {
            form.value.avatar = res.fileName
        }else {
                              uni.showToast({
                                  title: res.msg,
                                  icon: 'none'
                              })
                          }
    })
}


const save = () => {
    uForm.value.validate().then(valid => {
        console.log(valid)
        if (valid) {
            userUpdate({
                userAvatar:form.value.avatar,
                userNickname:form.value.name,
                phoneNumber:form.value.phoneNumber
            }).then(res => {
                uni.hideLoading();
                if(res.code == 200) {

                    let userInfo = uni.getStorageSync('userInfo');
                    userInfo.nikeName = form.value.name;
                    userInfo.phone = form.value.phone;
                    userInfo.userAvatar = form.value.avatar;
                    uni.setStorageSync('userInfo', userInfo)
                    store.user.SET_USERINFO(userInfo)

                    uni.showToast({
                        title: '修改成功',
                        icon: 'none',
                        duration: 1000
                    })
                    
                }else {
                              uni.showToast({
                                  title: res.msg,
                                  icon: 'none'
                              })
                          }
            }).catch(err => {
                uni.hideLoading();
            })
        }
    }).catch(err => {
        console.log(err)
    })
}


</script>

<style lang="scss" scoped>
.information-update {
    height:100vh;

    .avatar-btn {
        padding:0;
        margin:0;
        border:0;
        background:none;
        line-height: inherit;

        &:after {
            border:0;
        }
    }
    .information-update__body  {
        width: 460rpx;
    }
}
</style>
